from rest_framework import viewsets

from connection.models import CertificateTemplate
from connection.serializers import CertificateTemplateSerializer
from libs.decorators import permission_required
from libs.enums import Permission, LogModule
from log.services import log_service


class CertificateTemplateViewSet(viewsets.ModelViewSet):
    queryset = CertificateTemplate.objects.all()
    serializer_class = CertificateTemplateSerializer
    ordering_fields = ('id',)
    log_module = LogModule.CERT_TEMPLATE.value

    @permission_required([Permission.TEMPLATE_MANAGE.value])
    def create(self, request, *args, **kwargs):
        return super().create(request, *args, **kwargs)

    def perform_create(self, serializer):
        super().perform_create(serializer)
        log_service.build_create_log(self.request.user, serializer.instance, self.log_module, f'创建了授权书模版: {serializer.instance.name}')

    @permission_required([Permission.TEMPLATE_MANAGE.value])
    def update(self, request, *args, **kwargs):
        return super().update(request, *args, **kwargs)

    def perform_update(self, serializer):
        super().perform_update(serializer)
        log_service.build_update_log(self.request.user, serializer.instance, self.log_module, f'修改了授权书模版: {serializer.instance.name}')

    @permission_required([Permission.TEMPLATE_MANAGE.value])
    def partial_update(self, request, *args, **kwargs):
        return super().partial_update(request, *args, **kwargs)

    @permission_required([Permission.TEMPLATE_MANAGE.value])
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        log_service.build_delete_log(self.request.user, instance, self.log_module, f'删除了授权书模版: {instance.name}')
        return super().destroy(request, *args, **kwargs)
